package com.wzz.seckillone.activeMq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wzz.seckillone.pojo.SecKillMessage;
import com.wzz.seckillone.pojo.SeckillGoods;
import com.wzz.seckillone.pojo.SeckillOrder;
import com.wzz.seckillone.pojo.User;
import com.wzz.seckillone.service.GoodsService;
import com.wzz.seckillone.service.SeckillGoodsService;
import com.wzz.seckillone.service.SeckillOrderService;
import com.wzz.seckillone.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import javax.jms.MapMessage;
import javax.jms.TextMessage;

/**
 * @ProjectName: seckillOne
 * @Package: com.wzz.seckillone.activeMq
 * @ClassName: ActiveMqRecevieMsgByTopic
 * @Author: wzz
 * @Description: 订阅
 * @Date: 2022/3/21 15:06
 * @Version: 1.0
 */
@Component
@Slf4j
public class MqReceive {
    @Autowired
    private GoodsService goodsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SeckillOrderService seckillOrderService;

    @JmsListener(destination = "${myQueue}")
    public void getMsg(String message){
        log.info("收到消息"+message);
        /*
        * JSON.parseArray 转义[包裹的数据]
        * JSON.parseObject 转义{包裹的数据}
        * */
        JSONObject jsonObject = JSON.parseObject(message);

        String goodsId = (String) jsonObject.get("goodsId");
        User user = jsonObject.getObject("user", User.class);
        log.info(goodsId);
        log.info(user+"用户信息");

        GoodsVo goodsVo = goodsService.findGoodsVoById(goodsId);
        if (goodsVo.getStockCount() < 1){
            return;
        }
        //再次判断是否重复抢购
        SeckillOrder seckillOrder = (SeckillOrder) redisTemplate.opsForValue().get("order" + user.getUserId() + ":" + goodsId);
        if(seckillOrder != null){
            return;
        }
        //下单操作
        seckillOrderService.doSecKill(user,goodsVo);
    }
}
